<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>2_react生命周期(旧)</title>
  <!-- 引入React核心库 -->
  <script type="text/javascript" src="../js/17.0.2/react.development.js"></script>
  <!-- 引入react-dom,用于支持react操作DOM -->
  <script type="text/javascript" src="../js/17.0.2/react-dom.development.js"></script>
  <!-- 引入babel，用于把jsx转为js -->
  <script type="text/javascript" src="../js/babel.min.js"></script>
</head>

<body>
  <!-- <div id="test1"></div> -->
  <div id="test2"></div>

  <script type="text/babel">
    /*
      即将弃用                           改为
      componentWillMount===============>UNSAFE_componentWillMount
      componentWillUpdate==============>UNSAFE_componentWillUpdate
      componentWillReceiveProps =======>UNSAFE_componentWillReceiveProps
    */
    // 创建组件
    class Count extends React.Component {
      // 组件初始化一开始就加载
      constructor(props) {
        console.log('Count---constructor')
        super(props)
        this.state = {
          count: 0
        }
      }

      add = () => {
        const { count } = this.state
        this.setState({ count: count + 1 })
      }

      // 组件卸载
      death = () => {
        ReactDOM.unmountComponentAtNode(document.getElementById('test'))
      }

      // 组件强制更新
      force = () => {
        this.forceUpdate()
      }
      // 组件挂载后调用的钩子
      componentDidMount () {
        console.log('Count---componentDidMount')
      }

      // 组件卸载前调用的钩子
      componentWillUnmount () {
        console.log('Count---componentWillUnmount')
      }

      // 控制组件更新的“阀门”，必须写返回值（true,false）
      shouldComponentUpdate () {
        console.log('Count---shouldComponentUpdate')
        return true
      }

      // 必须是静态方法，且必须要有返回值null或者状态对象 =======>从props中得到一个衍生的状态
      static getDerivedStateFromProps (props, state) {
        console.log('getDerivedStateFromProps', props, state)
        if (state.count > props.count) {
          return props
        } else {
          return state
        }
      }

      // 在更新之前获取快照
      getSnapshotBeforeUpdate (preProps, preState) {
        console.log('getSnapshotBeforeUpdate', preProps, preState)
        return 'lll'
      }

      // 组件更新完毕时调用的钩子
      componentDidUpdate (preProps, preState, snapshot) {
        console.log('Count---componentDidUpdate', preProps, preState, snapshot)
      }

      // 组件挂载
      render () {
        console.log('Count---render')
        const { count } = this.state
        return (
          <div>
            <h1>当前的和为{count}</h1>
            <button onClick={this.add}>+1</button>
            <button onClick={this.death}>卸载组件</button>
            <button onClick={this.force}>不更改状态中的数据，强制更新</button>
          </div>
        )
      }
    }

    ReactDOM.render(<Count count={10} />, document.getElementById('test2'))
  </script>
</body>

</html>